package com.example.surfaceview_textureview.surfaceview_mediaplayer;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.surfaceview_textureview.R;

import java.io.IOException;

public class Main2Activity extends AppCompatActivity implements SurfaceHolder.Callback {
    private MediaPlayer mediaPlayer;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main2);
        try {
            initPlayer();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        initview();

    }

    private void initview() {
        //播放视频的
        surfaceView=findViewById(R.id.surface_view);
        surfaceHolder=surfaceView.getHolder();
        surfaceHolder.addCallback(this);//设置回调监听：获得surfaceView的生命周期

    }

    private void initPlayer() throws IOException {
        if(mediaPlayer==null){
            mediaPlayer=new MediaPlayer();
        }
        mediaPlayer.reset();
        mediaPlayer.setDataSource("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4");
        mediaPlayer.prepare();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {//准备完毕了
                mediaPlayer.start();
            }
        });

    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        if(holder != null){
            mediaPlayer.setDisplay(holder);
        }

    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        if(mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}